import React, { useState } from 'react';
import {
  Box,
  Container,
  Grid,
  Paper,
  Typography,
  FormGroup,
  FormControlLabel,
  Checkbox,
  Slider,
  Select,
  MenuItem,
  InputLabel,
  FormControl,
  Chip,
  IconButton,
  useTheme,
  useMediaQuery,
  Drawer,
  Button,
} from '@mui/material';
import FilterListIcon from '@mui/icons-material/FilterList';
import CloseIcon from '@mui/icons-material/Close';
import GameCard from '../components/GameCard'; // 我们稍后会创建这个组件

// 模拟数据
const mockGenres = [
  '动作', 'RPG', '策略', '模拟', '冒险', '射击', '体育', '竞速',
];

const mockPlatforms = [
  'PC', 'PlayStation 5', 'Xbox Series X', 'Nintendo Switch',
];

const mockReleaseYears = [
  2024, 2023, 2022, 2021, 2020,
];

const mockGames = [
  {
    id: 1,
    title: "赛博朋克 2077",
    imageUrl: "https://via.placeholder.com/300x200",
    tags: ["动作", "RPG", "开放世界"],
    rating: 4.5,
    price: "¥298",
  },
  {
    id: 2,
    title: "艾尔登法环",
    imageUrl: "https://via.placeholder.com/300x200",
    tags: ["动作", "RPG", "魂类"],
    rating: 4.8,
    price: "¥398",
  },
  {
    id: 3,
    title: "星空",
    imageUrl: "https://via.placeholder.com/300x200",
    tags: ["RPG", "科幻", "开放世界"],
    rating: 4.2,
    price: "¥498",
  },
  {
    id: 4,
    title: "博德之门 3",
    imageUrl: "https://via.placeholder.com/300x200",
    tags: ["RPG", "策略", "奇幻"],
    rating: 4.9,
    price: "¥398",
  },
  {
    id: 5,
    title: "死亡搁浅",
    imageUrl: "https://via.placeholder.com/300x200",
    tags: ["动作", "冒险", "剧情"],
    rating: 4.4,
    price: "¥298",
  },
  {
    id: 6,
    title: "荒野大镖客：救赎2",
    imageUrl: "https://via.placeholder.com/300x200",
    tags: ["动作", "冒险", "开放世界"],
    rating: 4.7,
    price: "¥258",
  },
];

interface FilterState {
  genres: string[];
  platforms: string[];
  releaseYears: number[];
  priceRange: [number, number];
  rating: number;
}

const Categories: React.FC = () => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  const [mobileFilterOpen, setMobileFilterOpen] = useState(false);
  const [sortBy, setSortBy] = useState('newest');
  const [filters, setFilters] = useState<FilterState>({
    genres: [],
    platforms: [],
    releaseYears: [],
    priceRange: [0, 500],
    rating: 0,
  });

  const handleFilterChange = (
    category: keyof FilterState,
    value: string | number
  ) => {
    setFilters(prev => {
      if (Array.isArray(prev[category])) {
        const array = prev[category] as Array<any>;
        const newArray = array.includes(value)
          ? array.filter(item => item !== value)
          : [...array, value];
        return { ...prev, [category]: newArray };
      }
      return { ...prev, [category]: value };
    });
  };

  const handlePriceRangeChange = (event: Event, newValue: number | number[]) => {
    setFilters(prev => ({
      ...prev,
      priceRange: newValue as [number, number],
    }));
  };

  const clearFilters = () => {
    setFilters({
      genres: [],
      platforms: [],
      releaseYears: [],
      priceRange: [0, 500],
      rating: 0,
    });
  };

  const FilterContent = () => (
    <Box sx={{ p: 2 }}>
      <Box sx={{ mb: 3, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Typography variant="h6">筛选</Typography>
        <Button onClick={clearFilters} size="small">
          清除全部
        </Button>
      </Box>

      {/* 游戏类型 */}
      <Box sx={{ mb: 4 }}>
        <Typography variant="subtitle1" gutterBottom>
          游戏类型
        </Typography>
        <FormGroup>
          {mockGenres.map(genre => (
            <FormControlLabel
              key={genre}
              control={
                <Checkbox
                  checked={filters.genres.includes(genre)}
                  onChange={() => handleFilterChange('genres', genre)}
                  size="small"
                />
              }
              label={genre}
            />
          ))}
        </FormGroup>
      </Box>

      {/* 平台 */}
      <Box sx={{ mb: 4 }}>
        <Typography variant="subtitle1" gutterBottom>
          平台
        </Typography>
        <FormGroup>
          {mockPlatforms.map(platform => (
            <FormControlLabel
              key={platform}
              control={
                <Checkbox
                  checked={filters.platforms.includes(platform)}
                  onChange={() => handleFilterChange('platforms', platform)}
                  size="small"
                />
              }
              label={platform}
            />
          ))}
        </FormGroup>
      </Box>

      {/* 发售年份 */}
      <Box sx={{ mb: 4 }}>
        <Typography variant="subtitle1" gutterBottom>
          发售年份
        </Typography>
        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
          {mockReleaseYears.map(year => (
            <Chip
              key={year}
              label={year}
              clickable
              color={filters.releaseYears.includes(year) ? 'primary' : 'default'}
              onClick={() => handleFilterChange('releaseYears', year)}
              size="small"
            />
          ))}
        </Box>
      </Box>

      {/* 价格范围 */}
      <Box sx={{ mb: 4 }}>
        <Typography variant="subtitle1" gutterBottom>
          价格范围
        </Typography>
        <Box sx={{ px: 2 }}>
          <Slider
            value={filters.priceRange}
            onChange={handlePriceRangeChange}
            valueLabelDisplay="auto"
            min={0}
            max={500}
            step={10}
          />
          <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
            <Typography variant="body2">
              ¥{filters.priceRange[0]}
            </Typography>
            <Typography variant="body2">
              ¥{filters.priceRange[1]}
            </Typography>
          </Box>
        </Box>
      </Box>
    </Box>
  );

  return (
    <Container maxWidth="xl" sx={{ py: 4 }}>
      {/* 移动端筛选按钮 */}
      {isMobile && (
        <Box sx={{ mb: 2 }}>
          <Button
            startIcon={<FilterListIcon />}
            onClick={() => setMobileFilterOpen(true)}
            variant="outlined"
            fullWidth
          >
            筛选
          </Button>
        </Box>
      )}

      <Grid container spacing={3}>
        {/* 筛选侧边栏 */}
        {!isMobile ? (
          <Grid item xs={12} md={3} lg={2}>
            <Paper
              elevation={0}
              sx={{
                position: 'sticky',
                top: theme.spacing(2),
                maxHeight: 'calc(100vh - 100px)',
                overflowY: 'auto',
              }}
            >
              <FilterContent />
            </Paper>
          </Grid>
        ) : (
          <Drawer
            anchor="left"
            open={mobileFilterOpen}
            onClose={() => setMobileFilterOpen(false)}
          >
            <Box sx={{ width: 280 }}>
              <Box sx={{ p: 2, display: 'flex', justifyContent: 'flex-end' }}>
                <IconButton onClick={() => setMobileFilterOpen(false)}>
                  <CloseIcon />
                </IconButton>
              </Box>
              <FilterContent />
            </Box>
          </Drawer>
        )}

        {/* 游戏列表区域 */}
        <Grid item xs={12} md={9} lg={10}>
          {/* 排序和结果计数 */}
          <Box
            sx={{
              mb: 3,
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              flexWrap: 'wrap',
              gap: 2,
            }}
          >
            <Typography variant="h6">
              找到 42 个游戏
            </Typography>
            <FormControl size="small" sx={{ minWidth: 200 }}>
              <InputLabel>排序方式</InputLabel>
              <Select
                value={sortBy}
                label="排序方式"
                onChange={(e) => setSortBy(e.target.value)}
              >
                <MenuItem value="newest">最新发布</MenuItem>
                <MenuItem value="popular">最受欢迎</MenuItem>
                <MenuItem value="rating">评分最高</MenuItem>
                <MenuItem value="price-asc">价格从低到高</MenuItem>
                <MenuItem value="price-desc">价格从高到低</MenuItem>
              </Select>
            </FormControl>
          </Box>

          {/* 活跃筛选器 */}
          <Box sx={{ mb: 3, display: 'flex', flexWrap: 'wrap', gap: 1 }}>
            {filters.genres.map(genre => (
              <Chip
                key={genre}
                label={genre}
                onDelete={() => handleFilterChange('genres', genre)}
                size="small"
              />
            ))}
            {filters.platforms.map(platform => (
              <Chip
                key={platform}
                label={platform}
                onDelete={() => handleFilterChange('platforms', platform)}
                size="small"
              />
            ))}
            {filters.releaseYears.map(year => (
              <Chip
                key={year}
                label={year}
                onDelete={() => handleFilterChange('releaseYears', year)}
                size="small"
              />
            ))}
          </Box>

          {/* 游戏网格 */}
          <Grid container spacing={2}>
            {mockGames.map((game) => (
              <Grid item key={game.id} xs={12} sm={6} md={4} lg={3}>
                <GameCard game={game} />
              </Grid>
            ))}
          </Grid>
        </Grid>
      </Grid>
    </Container>
  );
};

export default Categories;
